<?php
import("ORG.Util.Function");
import("@.Org.Utils");
import("@.Org.CommonTool");
import("@.Org.BonusTool");


class BonusAction extends CommonAction{	
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	/**
	 * 红包类型分类
	 * Enter description here ...
	 */
	public function bonus_type_list(){

		$sort_flag  = 	sort_flag($list['filter']);
				
	    $this->assign($sort_flag['tag'], $sort_flag['img']); // 默认排序字段
	    	    
	    $sql_bonus_type_list 		= 	get_sql_bonus_type_list();
	    
	    $param 				= 	array(
			'result'	=> $sql_bonus_type_list,					//分页用的数组或sql
			'listvar'	=> 'type_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'Bonus:bonus_type',				//ajax更新模板
		);	    
	    
		$this->page_bonus_type_list($param); // 分页
		$this->display('bonus_type');
	}
	
	
	/**
	 * 红包类型列表分页
	 * Enter description here ...
	 */
	public function page_bonus_type_list($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');	//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		/////////////////////////////// 格式化数据
		$CommonModel	=	new CommonModel();
		
	    /* 获得所有红包类型的发放数量 */
	    $sql 		= 	"SELECT bonus_type_id, COUNT(*) AS sent_count".
	            		" FROM " .'ybr_user_bonus' .
	            		" GROUP BY bonus_type_id";
	    $res 		= 	M()->query($sql);
	
	    $sent_arr 	= 	array();
	    foreach($res as $row){
	    	 $sent_arr[$row['bonus_type_id']] = $row['sent_count'];
	    }
	
	    /* 获得所有红包类型的发放数量 */
	    $sql 		= 	"SELECT bonus_type_id, COUNT(*) AS used_count".
	            		" FROM " .'ybr_user_bonus' .
	            		" WHERE used_time > 0".
	            		" GROUP BY bonus_type_id";
	    $res 		= 	M()->query($sql);
	
	    $used_arr 	= 	array();
	    
	    foreach($res as $row){
	    	$used_arr[$row['bonus_type_id']] = $row['used_count'];
	    }
		
	    $lang_send_by			=	L('send_by'); // 发放红包的标准
	    
		foreach($voList as $key => $row){
			$row['send_by'] 	= 	$lang_send_by[$row['send_type']];
        	$row['send_count'] 	= 	isset($sent_arr[$row['type_id']]) ? $sent_arr[$row['type_id']] : 0;
        	$row['use_count'] 	= 	isset($used_arr[$row['type_id']]) ? $used_arr[$row['type_id']] : 0;
        	$voList[$key] 		= 	$row;
		}	
		/////////////////////////////// 格式化数据
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	/**
	 * 添加红包
	 * Enter description here ...
	 */
	public function add_bonus_type(){
	    
		$lang_send_by					=	L('send_by');		
	    $this->assign('lang_send_by',       $lang_send_by);
	    	
	    $this->assign('action',       'add_bonus_type_ok');	
	    $this->assign('form_act',     'insert');
	    $this->assign('cfg_lang',     $GLOBALS['_CFG']['lang']);
	    $this->assign('help_open',     true);
	
	   
	    
	    $next_month 					= 	local_strtotime('+1 months');
	    $bonus_arr['send_start_date']   = 	local_date('Y-m-d');
	    $bonus_arr['use_start_date']    = 	local_date('Y-m-d');
	    $bonus_arr['send_end_date']     = 	local_date('Y-m-d', $next_month);
	    $bonus_arr['use_end_date']      = 	local_date('Y-m-d', $next_month);	
	    $this->assign('bonus_arr',    $bonus_arr);	
	    $this->display('bonus_type_info');
	}
	
	/**
	 * 处理添加红包类型
	 * Enter description here ...
	 */
	public function add_bonus_type_ok(){
		
		$CommonModel	=	new CommonModel();
		
		/* 去掉红包类型名称前后的空格 */
	    $type_name   	= 	!empty($_POST['type_name']) ? trim($_POST['type_name']) : '';
	
	    /* 初始化变量 */
	    $type_id     	= 	!empty($_POST['type_id'])    ? intval($_POST['type_id'])    : 0;
	    $min_amount  	= 	!empty($_POST['min_amount']) ? intval($_POST['min_amount']) : 0;
	
	    /* 检查类型是否有重复 */
	    $sql 			= 	"SELECT COUNT(*) FROM " . 'ybr_bonus_type' . " WHERE type_name='$type_name'";
	    if ($CommonModel->getOne($sql) > 0){
	        $this->error(L('type_name_exist'));
	    }
	
	    /* 获得日期信息 */
	    $send_startdate = 	local_strtotime($_POST['send_start_date']);
	    $send_enddate   = 	local_strtotime($_POST['send_end_date']);
	    $use_startdate  = 	local_strtotime($_POST['use_start_date']);
	    $use_enddate    = 	local_strtotime($_POST['use_end_date']);
	
	    /* 插入数据库。 */
	    $sql 			= 	"INSERT INTO ".'ybr_bonus_type' . " (type_name, type_money,send_start_date,send_end_date,use_start_date,use_end_date,send_type,min_amount,min_goods_amount)
	    					VALUES ('$type_name',
	            			'$_POST[type_money]',
	            			'$send_startdate',
	            			'$send_enddate',
	            			'$use_startdate',
	            			'$use_enddate',
	            			'$_POST[send_type]',
	            			'$min_amount','" . floatval($_POST['min_goods_amount']) . "')";
	
	    $CommonModel->query($sql);
	    /* 记录管理员操作 */
	    admin_log($_POST['type_name'], 'add', 'bonustype');
	
	    /* 清除缓存 */
	    clear_cache();	
	    /* 提示信息 */	
	    //sys_msg($_LANG['add'] . "&nbsp;" .$_POST['type_name'] . "&nbsp;" . $_LANG['attradd_succed'],0, $link);
    	$this->success("操作成功",U('bonus/bonus_type_list'));    
	}
	
	
	/**
	 * 修改红包类型
	 * Enter description here ...
	 */
	public function mod_bonus_type(){

		$CommonModel	=	new CommonModel();
	    /* 获取红包类型数据 */
	    $type_id 		= 	!empty($_GET['type_id']) ? intval($_GET['type_id']) : 0;
	    $bonus_arr 		= 	$CommonModel->getRow("SELECT * FROM " . 'ybr_bonus_type' . "  WHERE type_id = '$type_id'");
	
	    $bonus_arr['send_start_date']   = local_date('Y-m-d', $bonus_arr['send_start_date']);
	    $bonus_arr['send_end_date']     = local_date('Y-m-d', $bonus_arr['send_end_date']);
	    $bonus_arr['use_start_date']    = local_date('Y-m-d', $bonus_arr['use_start_date']);
	    $bonus_arr['use_end_date']      = local_date('Y-m-d', $bonus_arr['use_end_date']);
	
	    $lang_send_by					=	L('send_by');		
	    $this->assign('lang_send_by',       $lang_send_by);
	    
	    $this->assign('form_act',    'update');
	    $this->assign('action',    	 'mod_bonus_type_ok');
	    $this->assign('bonus_arr',   $bonus_arr);	
		$this->display('bonus_type_info');
	}
	
	/**
	 * 处理修改红包类型
	 * Enter description here ...
	 */
	public function mod_bonus_type_ok(){
		
		$CommonModel		=	new CommonModel();
		 /* 获得日期信息 */
	    $send_startdate 	=	local_strtotime($_POST['send_start_date']);
	    $send_enddate   	= 	local_strtotime($_POST['send_end_date']);
	    $use_startdate  	= 	local_strtotime($_POST['use_start_date']);
	    $use_enddate    	= 	local_strtotime($_POST['use_end_date']);
	
	    /* 对数据的处理 */
	    $type_name   		= 	!empty($_POST['type_name'])  ? trim($_POST['type_name'])    : '';
	    $type_id     		= 	!empty($_POST['type_id'])    ? intval($_POST['type_id'])    : 0;
	    $min_amount  		= 	!empty($_POST['min_amount']) ? intval($_POST['min_amount']) : 0;
	
	    $sql 				= 	"UPDATE " .'ybr_bonus_type'. " SET ".
	           					"type_name       = '$type_name', ".
	           					"type_money      = '$_POST[type_money]', ".
	           					"send_start_date = '$send_startdate', ".
	           					"send_end_date   = '$send_enddate', ".
	           					"use_start_date  = '$use_startdate', ".
	           					"use_end_date    = '$use_enddate', ".
	           					"send_type       = '$_POST[send_type]', ".
	           					"min_amount      = '$min_amount', " .
	           					"min_goods_amount = '" . floatval($_POST['min_goods_amount']) . "' ".
	           					"WHERE type_id   = '$type_id'";
	
	  	M()->query($sql);
	   	/* 记录管理员操作 */
	   	admin_log($_POST['type_name'], 'edit', 'bonustype');
	
	   	/* 清除缓存 */
	   	clear_cache();		   
   		$this->success("操作成功",U('bonus/bonus_type_list'));
	}
	
	/**
	 * 删除红包类型
	 * Enter description here ...
	 */
	public function remove_bonus_type(){

		import("@.Plugs.Exchange");	
			
	    $id 		= 	intval($_GET['id']);

	    $exc		=	new Exchange("ybr_bonus_type", null,  'type_id', 'type_name');	    
	    $exc->drop($id);	
	    
	    /* 更新商品信息 */
	    M()->query("UPDATE " .'ybr_goods' . " SET bonus_type_id = 0 WHERE bonus_type_id = '$id'");	
	    /* 删除用户的红包 */
	    M()->query("DELETE FROM " .'ybr_user_bonus' . " WHERE bonus_type_id = '$id'");	
	    //$url = 'bonus.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);
	    $this->success("操作成功",U('bonus/bonus_type_list'));
	}
		
	/**
	 * 红包列表
	 * Enter description here ...
	 */
	public function bonus_list(){
		
		$this->assign("bonus_type",$_REQUEST['bonus_type']);
	    /* 赋值是否显示红包序列号 */
	    $bonus_type 			= 	bonus_type_info(intval($_REQUEST['bonus_type']));
	    if ($bonus_type['send_type'] == SEND_BY_PRINT){
	        $this->assign('show_bonus_sn', 1);
	    }	
	    /* 赋值是否显示发邮件操作和是否发过邮件 */
	    elseif ($bonus_type['send_type'] == SEND_BY_USER){
	        $this->assign('show_mail', 1);
	    }
	
	    $this->assign('bonus_list',   $list['item']);
	
	    $sort_flag 			 =	 sort_flag($list['filter']);	    
	    $this->assign($sort_flag['tag'], $sort_flag['img']); // 默认排序字段		
		
	    // 列表
	    $sql_bonus_list		= 	get_sql_bonus_list();
	    
	    $param 				= 	array(
			'result'	=> $sql_bonus_list,					//分页用的数组或sql
			'listvar'	=> 'bonus_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'Bonus:bonus_list',				//ajax更新模板
		);	    
	    
		$this->page_bonus_list($param); // 分页
		$this->display();
	}
	
	
	/**
	 * 红包列表分页
	 * Enter description here ...
	 */
	public function page_bonus_list($param){
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		//=========================== 格式化数据
	   	$lang_mail_status		=	L('mail_status');
	    foreach ($voList AS $key => $val){
	        $voList[$key]['used_time'] 		= 	$val['used_time'] == 0 ?  L('no_use') : local_date($GLOBALS['_CFG']['date_format'], $val['used_time']);
	        $voList[$key]['emailed'] 		= 	$lang_mail_status[$voList[$key]['emailed']];
    	}		
		//=========================== 格式化数据
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;
	}
	
	
	/**
	 * 删除红包
	 * Enter description here ...
	 */
	public function remove_bonus(){
		
		$bonus_type		=	$_GET['bonus_type'];	
	    $id 			= 	intval($_GET['id']);	
	    M()->query("DELETE FROM " .'ybr_user_bonus'. " WHERE bonus_id='$id'");			
		$this->success("操作成功",U('bonus/bonus_list') . '?bonus_type=' . $bonus_type);
	}
	
	
	public function send_bonus(){
	
		$CommonModel			=	new CommonModel();
		
	    /* 取得参数 */
	    $id = !empty($_REQUEST['id'])  ? intval($_REQUEST['id'])  : '';
	
	    if ($_REQUEST['send_by'] == SEND_BY_USER){
	        $this->assign('id',           $id);
	        $this->assign('ranklist',     get_rank_list());	
	        $this->display('bonus_by_user');
	    }
	    elseif ($_REQUEST['send_by'] == SEND_BY_GOODS){
	        /* 查询此红包类型信息 */
	        $bonus_type 		= 	$CommonModel->getRow("SELECT type_id, type_name FROM " . 'ybr_bonus_type' . "  WHERE type_id='$_REQUEST[id]'");
	
	        /* 查询红包类型的商品列表 */
	        $goods_list 		= 	get_bonus_goods($_REQUEST['id']);
	
	        /* 查询其他红包类型的商品 */
	        $sql 				= 	"SELECT goods_id FROM " .'ybr_goods' . "  WHERE bonus_type_id > 0 AND bonus_type_id <> '$_REQUEST[id]'";
	        $other_goods_list 	= 	$CommonModel->getCol($sql);
	        $this->assign('other_goods', join(',', $other_goods_list));
			
	        $GoodsModel			=	new GoodsModel();
	        /* 模板赋值 */
	        $this->assign('cat_list',    $GoodsModel->cat_list());
	        $this->assign('brand_list',  get_brand_list());
	
	        $this->assign('bonus_type',  $bonus_type);
	        $this->assign('goods_list',  $goods_list);
	
	        $this->display('bonus_by_goods');
	    }
	    elseif ($_REQUEST['send_by'] == SEND_BY_PRINT){
	        $this->assign('type_list',    get_bonus_type());	
	        $this->display('bonus_by_print');
	    }
	}
	
	
	
	public function send_by_user(){
		
		$CommonModel		=	new CommonModel();
		
		t($_REQUEST);
		
		$user_list  		=	array();
	    $start      		= 	empty($_REQUEST['start']) ? 0 : intval($_REQUEST['start']);
	    $limit      		= 	empty($_REQUEST['limit']) ? 10 : intval($_REQUEST['limit']);
	    $validated_email 	= 	empty($_REQUEST['validated_email']) ? 0 : intval($_REQUEST['validated_email']);
	    $send_count 		= 	0;
		
	    if (isset($_REQUEST['send_rank'])){
	        /* 按会员等级来发放红包 */
	        $rank_id 		= 	intval($_REQUEST['rank_id']);
	
	        if ($rank_id > 0){
	            $sql 		= 	"SELECT min_points, max_points, special_rank FROM " . 'ybr_user_rank' . " WHERE rank_id = '$rank_id'";
	            $row 		= 	$CommonModel->getRow($sql);
	            
	            if ($row['special_rank']){
	                /* 特殊会员组处理 */
	                $sql 			= 	'SELECT COUNT(*) FROM ' . 'ybr_users' . " WHERE user_rank = '$rank_id'";
	                $send_count 	= 	$CommonModel->getOne($sql);
	                if($validated_email){
	                    $sql 		= 	'SELECT user_id, email, user_name FROM ' . 'ybr_users' .
	                            		" WHERE user_rank = '$rank_id' AND is_validated = 1".
	                            		" LIMIT $start, $limit";
	                }
	                else{
	                     $sql 		= 	'SELECT user_id, email, user_name FROM ' . 'ybr_users' .
	                                	" WHERE user_rank = '$rank_id'".
	                                	" LIMIT $start, $limit";
	                }
	            }
	            else{
	                $sql 			= 	'SELECT COUNT(*) FROM ' . ' ybr_users ' . " WHERE rank_points >= " . intval($row['min_points']) . " AND rank_points < " . intval($row['max_points']);
	                $send_count 	= 	$CommonModel->getOne($sql);
					
	                if($validated_email){
	                    $sql 		= 	'SELECT user_id, email, user_name FROM ' . 'ybr_users' .
	                        			" WHERE rank_points >= " . intval($row['min_points']) . " AND rank_points < " . intval($row['max_points']) .
	                        			" AND is_validated = 1 LIMIT $start, $limit";
	                }
	                else{
	                     $sql 		= 	'SELECT user_id, email, user_name FROM ' . 'ybr_users' .
	                        			" WHERE rank_points >= " . intval($row['min_points']) . " AND rank_points < " . intval($row['max_points']) .
	                        			" LIMIT $start, $limit";
	                }	
	            }
	
	            $user_list 			= 	$CommonModel->query($sql);
	            $count 				= 	count($user_list);	
	        }
	    }
	    elseif (isset($_REQUEST['send_user'])){
	        /* 按会员列表发放红包 */
	        /* 如果是空数组，直接返回 */
	        if (empty($_REQUEST['user'])){
	            //sys_msg($_LANG['send_user_empty'], 1);
	            $this->error(L('send_user_empty'));
	        }
	
	        $user_array 			= 	(is_array($_REQUEST['user'])) ? $_REQUEST['user'] : explode(',', $_REQUEST['user']);
	        $send_count 			= 	count($user_array);
	
	        $id_array   			= 	array_slice($user_array, $start, $limit);
	
	        /* 根据会员ID取得用户名和邮件地址 */
	        $sql 					= 	"SELECT user_id, email, user_name FROM " .'ybr_users' .
	               						" WHERE user_id " .db_create_in($id_array);
	        $user_list  			= 	$CommonModel->query($sql);
	        $count 					= 	count($user_list);
	    }
	
	    /* 发送红包 */
	    $loop       				=	0;
	    $bonus_type 				= 	bonus_type_info($_REQUEST['id']);
	
	    //$tpl 						= 	get_mail_template('send_bonus');
	    $today 						= 	local_date($GLOBALS['_CFG']['date_format']);
//	
	    foreach ($user_list AS $key => $val){
	        /* 发送邮件通知 */
//	        $this->assign('user_name',    $val['user_name']);
//	        $this->assign('shop_name',    $GLOBALS['_CFG']['shop_name']);
//	        $this->assign('send_date',    $today);
//	        $this->assign('sent_date',    $today);
//	        $this->assign('count',        1);
//	        $this->assign('money',        price_format($bonus_type['type_money']));
	
	        // $content 				= 	$this->fetch('str:' . $tpl['template_content']);
	
	        if (add_to_maillist($val['user_name'], $val['email'], $tpl['template_subject'], $content, $tpl['is_html'])){
	             /* 向会员红包表录入数据 */
	            $sql 				= 	"INSERT INTO " . 'ybr_user_bonus'  .
	                    				"(bonus_type_id, bonus_sn, user_id, used_time, order_id, emailed) " .
	                    				"VALUES ('$_REQUEST[id]', 0, '$val[user_id]', 0, 0, " .BONUS_MAIL_SUCCEED. ")";
	            $CommonModel->query($sql);
	        }
	        else{
	            /* 邮件发送失败，更新数据库 */
	            $sql 				= 	"INSERT INTO " . 'ybr_user_bonus'  .
	                    				"(bonus_type_id, bonus_sn, user_id, used_time, order_id, emailed) " .
	                    				"VALUES ('$_REQUEST[id]', 0, '$val[user_id]', 0, 0, " .BONUS_MAIL_FAIL. ")";
	            $CommonModel->query($sql);
	        }
	
	        if ($loop >= $limit){
	            break;
	        }
	        else{
	            $loop++;
	        }
	    }
	
	    //admin_log(addslashes($_LANG['send_bonus']), 'add', 'bonustype');
	    /*
	    if ($send_count > ($start + $limit)){
	        $href 					= 	"bonus.php?act=send_by_user&start=" . ($start+$limit) . "&limit=$limit&id=$_REQUEST[id]&";
	
	        if (isset($_REQUEST['send_rank'])){
	            $href 				.= 	"send_rank=1&rank_id=$rank_id";
	        }
	
	        if (isset($_REQUEST['send_user'])){
	            $href 				.= 	"send_user=1&user=" . implode(',', $user_array);
	        }
	
	        $link[] 				= 	array('text' => $_LANG['send_continue'], 'href' => $href);
	    }
	    */	
	    //$link[] 					= 	array('text' => $_LANG['back_list'], 'href' => 'bonus.php?act=list');	
	    //sys_msg(sprintf($_LANG['sendbonus_count'], $count), 0, $link);
	    $this->success("操作成功",U('bonus/bonus_type_list'));
	}
	
	
	
	
	
	
	
}








